﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using System.Web.UI;
using DotaHelp.Helpers;
using System.ServiceModel.Syndication;

namespace DotaHelp.Controllers
{
    
    public class PurchasesController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            model.Dispose();
            
        }

       
        public ActionResult List(int? page, string orderBy)
        {
			var purchases = model.Purchases.Include("PurchasesItems").Include("PurchasesItems.Item").Include("Hero").Where(p => !p.IsDeleted);
            return View(purchases.ByPage(page, orderBy, p => p.Raiting, p => p.Date, ViewData, HttpContext).ToArray());
        }       
         

        public ActionResult Add(int id)
        {
			ViewBag.Items = model.Items.Include("Recipes").OrderBy(i => i.Price).ToArray();            
			Hero hero = ViewBag.Hero = model.Heroes.Include("PurchaseHeroRules").First(h => h.Id == id);
            ViewBag.UserName = Request.GetUserName();
			ViewBag.Rules = hero.PurchaseHeroRules.Where(_ => !_.IsDeleted && _.Raiting >= 0).ToArray();
			ViewBag.ItemRules = model.PurchaseItemRules.Where(r => !r.IsDeleted && r.Raiting >= 0).ToArray();
            return View();
        }

        [HttpPost]
        public ActionResult Add(int heroId, string author, string comment, string password, string items, int warnings)
        {
            Response.SaveUserName(author);

            var p = new Purchase()
            {
                IpAddress = Request.ServerVariables["REMOTE_ADDR"],
                Date = DateTime.UtcNow.NowByAstana(),               
                Raiting = Math.Abs(warnings) * -10,
                Author = ControllerContext.HttpContext.PrepareUserName(author),
                Comment = comment,
                HeroId = heroId,
                Password = password
            };

            p.PurchasesItems.Add(new PurchasesItem() { ItemId = -1, Position = 7 });
            p.PurchasesItems.Add(new PurchasesItem() { ItemId = -1, Position = 14 });
            
            foreach (var row in items.Split(',').Select(_=>_.Split('|')))
            {
                p.PurchasesItems.Add(new PurchasesItem() { ItemId = int.Parse(row[1]), Position = int.Parse(row[0]) });
            }
            
            model.Purchases.AddObject(p);
            model.SaveChanges();
            

            return RedirectToRoute("Purchase", new { id = p.Id }); 
        }

        [Authorize(Roles="Admin")]
        public void Delete(int id)
        {
            var p = model.Purchases.First(i => i.Id == id);
            p.IsDeleted = true;
            model.SaveChanges();           
        }
       
        public ActionResult ChooseHero()
        {
            return View(model.Heroes);
        }

        [Sitemap(typeof(Purchase), "Date")]
        public ActionResult Details(int id)
        {
			var purchase = model.Purchases.Include("PurchasesItems").Include("PurchasesItems.Item").Include("Hero").First(p => p.Id == id);
            return View(purchase);
        }
                
        public ActionResult ListForHero(int heroId)
        {
			var list = model.Purchases
				.Include("PurchasesItems")
				.Include("PurchasesItems.Item")
				.Where(p => !p.IsDeleted)
				.Where(p => p.HeroId == heroId)
				.OrderByDescending(a => a.Raiting)
				.OrderBy(a => a.Date);

            return Request.IsAjaxRequest() ? (ActionResult)PartialView(list) : View(list);
        }

        [ChildActionOnly]
        public string Rating(int id, bool isPlus)
        {
            var purchase = model.Purchases.First(p => p.Id == id);
            purchase.Raiting += isPlus ? 1 : -1;
            model.SaveChanges();
            return purchase.Raiting.ToString();           
        } 

        public ActionResult One(int id, bool showHero = true, bool isSmall = true)
        {
            ViewData["ShowHero"] = showHero;
            if (isSmall) ViewData["Small"] = true;

			var purchace = model.Purchases.Include("PurchasesItems").Include("PurchasesItems.Item").Include("Hero").FirstOrDefault(p => p.Id == id);
            return purchace != null ? (ActionResult)PartialView(purchace) 
                : new ContentResult() { Content = "@" + id };
        }

		[ChildActionOnly]
		public ActionResult OneObject(Purchase purchase, bool showComments = false)
		{
			ViewData["ShowHero"] = true;
			ViewData["ShowCaption"] = true;
			ViewData["ShowComments"] = showComments;
			return PartialView("One", purchase);
		}


        [ChildActionOnly]
        [Rss]
        public IEnumerable<SyndicationItem> Rss()
        {
            var url = new UrlHelper(Request.RequestContext);
            
            foreach (var c in model.Purchases.OrderByDescending(_ => _.Date).Take(50))
            {
                yield return new SyndicationItem("Закуп", c.Comment, new Uri(url.GetBaseUrl(), url.Action("Details", "Purchases", new { id = c.Id })), "p" + c.Id, c.Date);
            }
        } 
    }
}
